use super::common::{
    combine_markdown_parser, make_markdown_pack_parser, make_skip_parser, EmphasisParser,
    HtmlToMarkdownHandler, ParseError,
};
use crate::html_node::YsNode;

// 知乎markdown解析器
pub fn zhihu_markdown_parser() -> impl HtmlToMarkdownHandler {
    let parser = make_markdown_pack_parser();
    let skip_parser = make_skip_parser(Box::new(|node| {
        node.get_tag().as_deref() == Some("noscript")
    }));

    struct ImageFigureParser;
    impl HtmlToMarkdownHandler for ImageFigureParser {
        fn handle(
            &self,
            node: &YsNode,
            handler: &dyn HtmlToMarkdownHandler,
        ) -> Result<String, ParseError> {
            if node.get_tag().as_deref() == Some("figure") {
                let div_node = node.get_children_elements();
                let img_wrap = div_node.get(1).unwrap().get_children_elements();
                let img_node = img_wrap.get(0).unwrap();
                let img_url = img_node.get_attribute("data-original").unwrap();
                let figcaption_text = match div_node.get(2) {
                    Some(node) => handler.handle(node, handler).unwrap(),
                    None => String::new(),
                };
                Ok(format!("![{}]({})\n\n", figcaption_text, img_url))
            } else {
                Err(ParseError::UnSupportedNode(
                    node.get_tag().unwrap_or_default().to_string(),
                ))
            }
        }
    }
    let new_parser = combine_markdown_parser(vec![
        Box::new(skip_parser),
        Box::new(EmphasisParser::new_with_tag(
            "b".to_string(),
            "i".to_string(),
        )),
        Box::new(ImageFigureParser),
        Box::new(parser),
    ]);
    new_parser
}

#[cfg(test)]
mod tests {
    use ysbase::func::{read_file, write_file};

    use super::*;
    use scraper::Html;

    #[test]
    fn test_zhihu_markdown_parser() {
        let html = read_file("test_resource/zhihu_article.html");
        let fragment = Html::parse_fragment(&html);
        let root = fragment.root_element();
        let first = root.first_child().unwrap();
        let node = YsNode::new(first);
        let parser = zhihu_markdown_parser();
        let markdown = parser.handle(&node, &parser).expect("无法解析该节点");
        write_file("test_resource/zhihu_article.md", &markdown);
    }
}
